package com.buaa.aimall.goodsModule.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.goodsModule.Entity.GoodsOrderAppealWorkOrderEntity;
import com.buaa.aimall.goodsModule.DTO.FilterGoodsOrderAppealWorkOrderDTO;
import com.buaa.aimall.goodsModule.DTO.ProcessGoodsOrderAppealDTO;
import com.buaa.aimall.Utils.Enum.WorkOrderStatusEnum;
import com.buaa.aimall.Utils.Exception.BusinessException;
import com.buaa.aimall.goodsModule.Enum.GoodsTypeEnum;
import com.buaa.aimall.goodsModule.Mapper.GoodsOrderAppealWorkOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDateTime;


@Service
public class GoodsOrderAppealWorkOrderServiceImpl extends ServiceImpl<GoodsOrderAppealWorkOrderMapper, GoodsOrderAppealWorkOrderEntity> implements GoodsOrderAppealWorkOrderService {
    @Autowired
    private GoodsOrderService goodsOrderService;

    public Boolean createAppealWorkOrder(GoodsOrderAppealWorkOrderEntity goodsOrderAppealWorkOrderEntity) {
        if (this.isAppealWorkOrderExists(goodsOrderAppealWorkOrderEntity.getGoodsOrderID())) {
            throw new BusinessException("该订单对应的申诉已存在");
        }
        var goodsOrder = goodsOrderService.getById(goodsOrderAppealWorkOrderEntity.getGoodsOrderID());
        goodsOrderAppealWorkOrderEntity.setGoodsType(goodsOrder.getModelID() == null ? GoodsTypeEnum.COMPUTE : GoodsTypeEnum.MODEL);
        goodsOrderAppealWorkOrderEntity.setStatus(WorkOrderStatusEnum.PROCESSING);
        boolean result;
        try {
            result = this.save(goodsOrderAppealWorkOrderEntity);
        } catch (DataAccessException e) {
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException) {
                throw new BusinessException("外键约束失败: " + e.getMessage());
            }
            throw new BusinessException("数据库访问错误: " + e.getMessage());
        }
        return result;
    }

    private boolean isAppealWorkOrderExists(String id) {
        return this.lambdaQuery()
                .eq(GoodsOrderAppealWorkOrderEntity::getGoodsOrderID, id)
                .count() > 0;
    }

    public Boolean processAppeal(ProcessGoodsOrderAppealDTO processGoodsOrderAppealDTO) {
        GoodsOrderAppealWorkOrderEntity goodsOrderAppealWorkOrderEntity = getById(processGoodsOrderAppealDTO.getId());
        if (goodsOrderAppealWorkOrderEntity == null)
            throw new BusinessException("不存在该工单");
        if (processGoodsOrderAppealDTO.getStatus() == null)
            throw new BusinessException("status填写错误");
        goodsOrderAppealWorkOrderEntity.setProcessorId(processGoodsOrderAppealDTO.getProcessorID());
        goodsOrderAppealWorkOrderEntity.setStatus(processGoodsOrderAppealDTO.getStatus());
        goodsOrderAppealWorkOrderEntity.setProcessTime(LocalDateTime.now());
        return updateById(goodsOrderAppealWorkOrderEntity);
    }

    public PageReturnResult<GoodsOrderAppealWorkOrderEntity> filterAppealWorkOrder(FilterGoodsOrderAppealWorkOrderDTO filterGoodsOrderAppealWorkOrderDTO) {
        PageReturnResult<GoodsOrderAppealWorkOrderEntity> result = new PageReturnResult<>();
        LambdaQueryWrapper<GoodsOrderAppealWorkOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        Integer pageSize = filterGoodsOrderAppealWorkOrderDTO.getPageSize();
        Integer currentPage = filterGoodsOrderAppealWorkOrderDTO.getCurrentPage();

        // 根据 FilterAppealWorkOrderDTO 中的字段动态构建查询条件
        if (filterGoodsOrderAppealWorkOrderDTO.getId() != null)
            queryWrapper.eq(GoodsOrderAppealWorkOrderEntity::getId, filterGoodsOrderAppealWorkOrderDTO.getId());
        if (filterGoodsOrderAppealWorkOrderDTO.getModelOrderID() != null)
            queryWrapper.eq(GoodsOrderAppealWorkOrderEntity::getGoodsOrderID, filterGoodsOrderAppealWorkOrderDTO.getModelOrderID());
        if (filterGoodsOrderAppealWorkOrderDTO.getAppealerID() != null)
            queryWrapper.eq(GoodsOrderAppealWorkOrderEntity::getAppealerID, filterGoodsOrderAppealWorkOrderDTO.getAppealerID());
        if (filterGoodsOrderAppealWorkOrderDTO.getStatus() != null)
            queryWrapper.eq(GoodsOrderAppealWorkOrderEntity::getStatus, filterGoodsOrderAppealWorkOrderDTO.getStatus());
        if (filterGoodsOrderAppealWorkOrderDTO.getProcessorID() != null)
            queryWrapper.eq(GoodsOrderAppealWorkOrderEntity::getProcessorId, filterGoodsOrderAppealWorkOrderDTO.getProcessorID());
        if (filterGoodsOrderAppealWorkOrderDTO.getCreateTimeStart() != null)
            queryWrapper.ge(GoodsOrderAppealWorkOrderEntity::getCreateTime, filterGoodsOrderAppealWorkOrderDTO.getCreateTimeStart());
        if (filterGoodsOrderAppealWorkOrderDTO.getCreateTimeEnd() != null)
            queryWrapper.le(GoodsOrderAppealWorkOrderEntity::getCreateTime, filterGoodsOrderAppealWorkOrderDTO.getCreateTimeEnd());
        if (filterGoodsOrderAppealWorkOrderDTO.getProcessTimeStart() != null)
            queryWrapper.ge(GoodsOrderAppealWorkOrderEntity::getProcessTime, filterGoodsOrderAppealWorkOrderDTO.getProcessTimeStart());
        if (filterGoodsOrderAppealWorkOrderDTO.getProcessTimeEnd() != null)
            queryWrapper.le(GoodsOrderAppealWorkOrderEntity::getProcessTime, filterGoodsOrderAppealWorkOrderDTO.getProcessTimeEnd());
        if (filterGoodsOrderAppealWorkOrderDTO.getContentKeyword() != null)
            queryWrapper.like(GoodsOrderAppealWorkOrderEntity::getContent, filterGoodsOrderAppealWorkOrderDTO.getContentKeyword());

        long totalCount = this.count(queryWrapper);
        result.setTotalCount(totalCount);

        // 分页处理
        if (pageSize != null && currentPage != null) {
            IPage<GoodsOrderAppealWorkOrderEntity> page = new Page<>(currentPage, pageSize);
            IPage<GoodsOrderAppealWorkOrderEntity> workOrderPage = page(page, queryWrapper);
            result.setRecords(workOrderPage.getRecords());
        } else {
            result.setRecords(list(queryWrapper));
        }

        return result;
    }
}
